package com.incom.log.server.mq.impl;

import com.incom.log.server.conf.redis.RedisConfig;
import com.incom.log.server.mq.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.InputStream;
import java.util.Properties;

public class RedisLogService extends LogService {

    private Logger log = null;

    private RedisConfig config;

    private JedisPool pool = null;

    public RedisLogService(RedisConfig config) {
        this.config = config;
        log = LoggerFactory.getLogger(config.getServiceNanme());
        if(config == null) {
            throw new NullPointerException("less redis config");
        }
        JedisPoolConfig pc = new JedisPoolConfig();
        try {
            pool = new JedisPool(pc, config.getHost(), config.getPort(), config.getTimeout());
            Jedis jedis = pool.getResource();
            if(config.getPassword() != null) {
                jedis.auth(config.getPassword());
            }
            jedis.select(config.getDbindex());
            jedis.exists("redis-test-ping");
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    public String read() {
        Jedis jedis = pool.getResource();
        if(config.getPassword() != null) {
            jedis.auth(config.getPassword());
        }
        jedis.select(config.getDbindex());
        String value = jedis.lpop(config.getKey());
        jedis.close();
        return value;
    }

    public void write(Object logMessage) {
        log.info(logMessage.toString());
    }
}
